package com.example.oauthauthorizationserver.business.dao;

import com.example.oauthauthorizationserver.business.bean.UserAuthorizeBean;
import com.example.oauthauthorizationserver.business.bean.UserBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class UserDao {
    @Autowired
    JdbcTemplate jdbcTemplate;

    // 根据账号查询用户信息
    public UserBean getUserByUsername(String username) {
        String sql = "select * from user where user_name = ?";
        // 连接数据库查询用户
        List<UserBean> list = jdbcTemplate.query(sql, new Object[] { username },
                new BeanPropertyRowMapper<>(UserBean.class));
        if (list != null && list.size() == 1) {
            return list.get(0);
        }
        return null;
    }

    // 根据用户id查询用户权限
    public List<String> getAuthorize(Long userId) {
        String sql = "SELECT * FROM user_authorize WHERE user_id =?";
        List<UserAuthorizeBean> list = jdbcTemplate.query(sql, new Object[] { userId },
                new BeanPropertyRowMapper<>(UserAuthorizeBean.class));
        List<String> authorizes = new ArrayList<>();
        list.forEach(c -> authorizes.add(c.getAuthorizeCode()));
        return authorizes;
    }
}
